/*
 DNN Content Builder - sourceforge.net/projects/dnncb
 Copyright (c) 2004-2008
 by Emerson Lopes (emersonlopes@gmail.com)

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
 documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
 the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
 to permit persons to whom the Software is furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all copies or substantial portions 
 of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
 TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
 CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 DEALINGS IN THE SOFTWARE.
*/

using System;

namespace DNNContentBuilder.UserControls
{
    /// <summary>
	///		Summary description.
	/// </summary>
	public class TaxonomyControl : DotNetNuke.Entities.Modules.PortalModuleBase
	{
		public const string resource = "~/DesktopModules/DNNContentBuilder/App_LocalResources/TaxonomyControl";

		#region Member Variables
		private readonly TaxonomyController taxonomyController = new TaxonomyController();
		private TaxonomyInfo taxonomyInfo = new TaxonomyInfo();
		#endregion

		#region Controls
		protected TaxonomyTreeView Taxonomies;
		protected System.Web.UI.HtmlControls.HtmlInputText txtTitle;
		protected System.Web.UI.HtmlControls.HtmlInputText CategoryTitle;
		protected System.Web.UI.WebControls.LinkButton btUpdate;
		protected System.Web.UI.WebControls.LinkButton btDelete;
		protected System.Web.UI.WebControls.LinkButton btCancel;
		protected System.Web.UI.HtmlControls.HtmlTextArea txtDescription;
		protected System.Web.UI.HtmlControls.HtmlInputHidden txtHidden;
        protected System.Web.UI.WebControls.Literal ltErrorMessage;
		#endregion

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.btUpdate.Click += new System.EventHandler(this.btUpdate_Click);
			this.btDelete.Click += new System.EventHandler(this.btDelete_Click);
			this.btCancel.Click += new System.EventHandler(this.btCancel_Click);
			this.Load += new System.EventHandler(this.Page_Load);
			this.Taxonomies.NodeClick += new FunkeLab.MyTreeView.OnNodeClickEventHandler(Taxonomies_NodeClick);


		}
		#endregion

		#region Event Handlers
		private void Page_Load(object sender, EventArgs e)
		{
			if (IsPostBack) 
			{
				this.btDelete.Attributes.Add("onClick", "javascript:return confirm('" + Commons.GetLocalizedString("label_ConfirmDelete", resource) + "')");
			}

			this.btCancel.Text = Commons.GetLocalizedString("button_Cancel", resource);
			this.btDelete.Text = Commons.GetLocalizedString("button_Delete", resource);
			this.btUpdate.Text = Commons.GetLocalizedString("button_Update", resource);

			if (!this.IsPostBack)
			{
				btDelete.Visible = false;
			}
		}

		private void Taxonomies_NodeClick (ref FunkeLab.MyTreeViewItem item) 
		{
			if (item.Value != "" && item.Value != "-1") 
			{
				taxonomyInfo = taxonomyController.GetItem(Int32.Parse(item.Value));

				txtHidden.Value			= taxonomyInfo.TaxonomyId.ToString();
				txtTitle.Value			= taxonomyInfo.Title;
				txtDescription.Value	= taxonomyInfo.Description;
				Taxonomies.SelectedNode = taxonomyInfo.ParentId;
				
				Taxonomies.BuildTree();

				btDelete.Visible = true;
			} 
			else 
			{
				this.ClearState();
			}
		}

		private void btUpdate_Click(object sender, EventArgs e)
		{
			if (txtTitle.Value == "" || txtDescription.Value == "") 
			{
				return;
			}

			int parentId = -1;

			TaxonomyInfo taxonomyInfo = new TaxonomyInfo();

			taxonomyInfo.Title		 = txtTitle.Value;
			taxonomyInfo.Description = txtDescription.Value;

			//TODO: UniqueID apparently has been changed by core team since version 3.0.10... I've fixed the code below, but I need to find a better way to retrieve the selected parent taxonomy...

			string radio = Taxonomies.UniqueID + "$";

			if (Page.Request.Form.Get(radio) != null) 
			{
				parentId = Int32.Parse(Page.Request.Form.Get(radio));
			}
			
			taxonomyInfo.ParentId = parentId;

			if (txtHidden.Value == "") 
			{	
				taxonomyController.Add(taxonomyInfo);
			} 
			else 
			{
				taxonomyInfo.TaxonomyId = Int32.Parse(txtHidden.Value);
				taxonomyController.Update(taxonomyInfo);
			}

			ClearState();
		}

		private void btDelete_Click(object sender, EventArgs e)
		{
			if (txtHidden.Value != "") 
			{
				try 
				{
				taxonomyController.Delete(Int32.Parse(txtHidden.Value));
				}
				catch (Exception ) {
                    ShowError(Commons.GetLocalizedString("label_CannotDeleteDueDependencies", resource), "");
				}
				
				this.ClearState();
			}
		}

		private void btCancel_Click(object sender, EventArgs e)
		{
			Response.Redirect(DotNetNuke.Common.Globals.NavigateURL());
		}

#pragma warning disable 168
        private void ShowError(string message, string error)
#pragma warning restore 168
        {
            ltErrorMessage.Visible = true;
            ltErrorMessage.Text = @"
			<script language='javascript'>
			<!-- 
			    alert('{0}') 
			-->
			</script>
			";
            ltErrorMessage.Text = String.Format(ltErrorMessage.Text, message).Replace("\r", "").Replace("\n", "");
            ltErrorMessage.Text = ltErrorMessage.Text.Replace("<!--", "\n<!--\n").Replace("-->", "\n-->\n");
        }
		#endregion

		#region Methods
		private void ClearState() 
		{
			Taxonomies.SelectedNode = -1;
			Taxonomies.BuildTree();

			btDelete.Visible = false;

			txtTitle.Value = "";
			txtDescription.Value = "";
			txtHidden.Value = "";
			
			//TODO: To find a way to rebuild dynamic form's taxonomy treeview
		}
		#endregion
	}
}
